class Sanke {
    head: HTMLElement;
    bodies: HTMLCollection;
    element: HTMLElement;
    constructor() {
        this.head = document.querySelector('#snake > li') as HTMLElement;
        this.bodies = document.getElementById('snake')!.getElementsByTagName('li');
        this.element = document.getElementById('snake')!;
    }
    get x() {
        return this.head.offsetLeft;
    }
    get y() {
        return this.head.offsetTop;
    }
    set X(value: number) {
        if (this.x === value) return;
        if (this.bodies[1] && (this.bodies[1] as HTMLElement).offsetLeft === value) {
            if (value > this.x) {
                value = this.x - 10
            } else {
                value = this.x + 10
            }
        };
        if (value < 0 || value > 290) {
            throw new Error('蛇撞墙了')
        }
        this.movebody()
        this.head.style.left = value + 'px';
        this.checkHeadBody()
    }
    set Y(value: number) {
        if (this.y === value) return;
        if (this.bodies[1] && (this.bodies[1] as HTMLElement).offsetTop === value) {
            if (value > this.y) {
                value = this.y - 10
            } else {
                value = this.y + 10
            }
        };

        if (value < 0 || value > 290) {
            throw new Error('蛇撞墙了')
        }
        this.movebody()
        this.head.style.top = value + 'px';
        this.checkHeadBody()
    }
    // 添加身体
    addHtml() {
        this.element.insertAdjacentHTML("beforeend", '<li></li>')
    }
    // 移动身体
    movebody() {
        for (let i = this.bodies.length - 1; i > 0; i--) {
            let X = (this.bodies[i - 1] as HTMLElement).offsetLeft;
            let Y = (this.bodies[i - 1] as HTMLElement).offsetTop;
            (this.bodies[i] as HTMLElement).style.top = Y + 'px';
            (this.bodies[i] as HTMLElement).style.left = X + 'px';
        }
    }
    // 检查有蛇头有没有和身体碰撞
    checkHeadBody() {
        for (let i = 1; i < this.bodies.length; i++) {
            let bd = this.bodies[i] as HTMLElement;
            if (this.x === bd.offsetLeft && this.y === bd.offsetTop) {
                throw new Error('撞到自己了')
            }
        }
    }
}


export default Sanke;